package com.dobbyspringside.examples.quickstart.web.account;

import com.dobbyspringside.examples.quickstart.entity.User;
import com.dobbyspringside.examples.quickstart.service.account.AccountService;
import com.dobbyspringside.examples.quickstart.service.account.ShiroDbRealm;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

/**
 * 用户修改自己资料的controller
 * Created by liguoqing on 2016/2/17.
 */
@Controller
@RequestMapping(value = "/profile")
public class ProfileController {

    @Autowired
    private AccountService accountService;


    /**
     * 取出Shiro中的当前用户Id.
     */
    private Long getCurrentUserId() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.id;
    }

    /**
     * 修改用户页面
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String updateForm(Model model) {
        Long id = getCurrentUserId();
        model.addAttribute("user", accountService.getUser(id));
        return "account/profile";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("user") User user) {
        accountService.updateUser(user);
        updateCurrentUserName(user.getName());
        return "redirect:/";
    }


    /**
     * 更新Shiro中当前用户的用户名.
     */
    private void updateCurrentUserName(String userName) {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        user.name = userName;
    }


}
